<template>
  <div class="app-container main">
    <el-tabs v-model="dataForm.status" @tab-click="handleClick">
      <el-tab-pane v-for="item in statusEnum" :key="item.id" :label="item.label" :name="item.value"></el-tab-pane>
    </el-tabs>
    <el-form :inline="true" :model="dataForm" size="mini">
      <el-form-item label="审批记录">
        <el-input v-model.trim="dataForm.bookName" style="width: 200px" placeholder="请输入审批记录" clearable
          show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker v-model="createTimeRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" clearable @change="changeDate">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button v-if="dataForm.status === '1'" type="primary" plain @click="showMoreControl">批量处理</el-button>
        <el-button v-if="dataForm.status === '2'" type="primary" plain @click="handelExportOut">导出</el-button>
        <el-button v-if="dataForm.status === '2'" type="primary" @click="handelUpload">上传<i class="el-icon-upload el-icon--right"></i></el-button>
      </el-form-item>
    </el-form>
    <div class="avue-form">
      <el-table ref="mainT" v-loading="dataListLoading" :data="dataList" border tooltip-effect="dark"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" show-overflow-tooltip width="55">
        </el-table-column>
        <el-table-column type="index" :index="indexMethod" header-align="center" align="center" label="序号"
          width="80"></el-table-column>
        <el-table-column prop="apply_code" header-align="center" align="center" label="申请编号"></el-table-column>
        <el-table-column prop="book_name" header-align="center" align="center" label="教材名称" show-overflow-tooltip />
        <el-table-column prop="course_name" header-align="center" align="center" label="课程名称"></el-table-column>
        <el-table-column prop="nick_name" header-align="center" align="center" label="发起人"></el-table-column>
        <el-table-column header-align="center" align="center" label="状态">
          <template slot-scope="scope">
            <span>{{ formateStatus(scope.row.audit_status) }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="申请时间">
          <template slot-scope="scope"> {{ parseTime(scope.row.create_time) }}</template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="操作" width="auto">
          <template slot-scope="scope">
            <el-button v-if="dataForm.status === '1'" type="text"
              @click="handleApplyFor(scope.row.id, scope.row.expert_leader_user_id)">处理</el-button>
            <el-button v-if="dataForm.status === '2'" type="text"
              @click="handleApplyFor(scope.row.id, scope.row.expert_leader_user_id)">查看详情</el-button>
            <el-button v-if="dataForm.status === '3'" type="text"
              @click="handleApplyFor(scope.row.id, scope.row.expert_leader_user_id)">查看详情</el-button>
            <el-button v-if="dataForm.status === '3' && scope.row.audit_status === 6" type="text" @click="showUploadFile(scope.row)">查看公示结果</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="avue-crud__pagination">
      <el-pagination :current-page="dataForm.current" :page-sizes="[10, 20, 50, 100]" :page-size="dataForm.size"
        :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"></el-pagination>
    </div>
    <el-dialog title="文件上传" :visible.sync="dialogUploadControl" @close="handleCloseUpload">
      <el-card class="box-card">
        <el-upload ref="upload" class="upload-demo" action="#" drag multiple :auto-upload="false"
          :on-change="handelUploadChange" :limit="1" :file-list="fileList">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传单个文件哦</div>
        </el-upload>
      </el-card>
      <div style="text-align: right; margin: 20px 0;">
        <el-button type="primary" @click="handelUloadResult(1)">确认</el-button>
        <el-button type="info" @click="handelUloadResult(0)">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量处理" width="1100px" :visible.sync="dialogMoreControl" @close="handerMoreClose">
      <div class="dialogMoreMain" style="display: flex;">
        <el-timeline :reverse="false" style="min-width: 200px;">
          <el-timeline-item v-for="(activity, index) in activities" :key="index" :color="activity.color">
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
        <div style="flex: 1;">
          <div>已选择 {{ multipleSelection.length }} 条信息</div>
          <el-table v-loading="dataListLoading" :data="multipleSelection" max-height="280" style="width: 720px" border tooltip-effect="dark">
            <el-table-column type="index" :index="indexMethod" header-align="center" align="center" label="序号"
              width="80"></el-table-column>
            <el-table-column width="150" prop="apply_code" header-align="center" align="center" label="申请编号"></el-table-column>
            <el-table-column width="150" prop="book_name" header-align="center" align="center" label="教材名称" show-overflow-tooltip />
            <el-table-column width="150" prop="course_name" header-align="center" align="center" label="课程名称"></el-table-column>
            <el-table-column width="150" prop="nick_name" header-align="center" align="center" label="发起人"></el-table-column>
            <el-table-column width="150" header-align="center" align="center" label="状态">
              <template slot-scope="scope">
                <span>{{ formateStatus(scope.row.audit_status) }}</span>
              </template>
            </el-table-column>
            <el-table-column width="150" header-align="center" align="center" label="申请时间">
              <template slot-scope="scope"> {{ parseTime(scope.row.create_time) }}</template>
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" label="操作" width="120">
              <template slot-scope="scope">
                <el-button type="primary" @click="handerDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="mainArea">
            <div class="title">复审</div>
            <div class="item">
              <div>评审专家</div>
              <div>
                <tags v-if="dialogMoreControl" @tagCHange="getTagData1" :managerList="managerList" :isMany="true" remark="老师" />
              </div>
            </div>
            <div class="item">
              <div>评审组长</div>
              <div>
                <tags v-if="dialogMoreControl" @tagCHange="getTagData2" :managerList="managerList" remark="老师" />
              </div>
            </div>
          </div>
          <div class="mainArea">
            <div class="title">终审</div>
            <div class="item">
              <div>学院院长</div>
              <div>
                <tags v-if="dialogMoreControl" @tagCHange="getTagData3" :managerList="managerList" remark="学院院长" />
              </div>
            </div>
            <div class="item">
              <div>学院书记</div>
              <div>
                <tags v-if="dialogMoreControl" @tagCHange="getTagData4" :managerList="managerList" remark="学院书记"/>
              </div>
            </div>
          </div>
          <el-row style="text-align: end; margin-top: 20px;">
            <el-button type="primary" @click.native="fnMoreNext(1)">完成</el-button>
            <el-button plain @click.native="fnMoreNext(0)">取消</el-button>
          </el-row>
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogHandlerVisible" @close="handerDetailClose" :destroy-on-close="true">
      <Approve ref="approve" v-if="dialogHandlerVisible" :applyId="applyForId" />
      <span slot="footer" class="dialog-footer" v-if="dataForm.status === '1'">
        <el-button @click="fnNext('2')">拒 绝</el-button>
        <el-button type="primary" @click="fnNext('1')">通 过</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getBookApplyList } from "@/api/bkmanage/application";
import { getUpdateApply, getUserList, getUploadFile, getAuditing,getExportExcel } from "@/api/bkmanage/auditing";
import { getBookApplyStatus, getBookApplyInfo } from "@/api/bkmanage/application";
import Approve from "../manage-auditing/approve.vue"
// import { exportExcel } from "../../../utils/excel"

import tags from "./components/tags.vue"
export default {
  name: "secretary-auditing",
  components: {
    tags,
    Approve
  },
  data() {
    return {
      multipleSelection: [], // 批量选择的数据
      // 状态列表
      statusEnum: [{
        value: '1',
        label: '待处理'
      }, {
        value: '2',
        label: '审核中'
      }, {
        value: '3',
        label: '已完成'
      }],
      // 时间线
      activities: [{
        content: '提交',
        color: '#409eff'
      }, {
        content: '初审',
        color: '#409eff'
      }, {
        content: '复审',
      }, {
        content: '终审',
      }, {
        content: '公示',
      }, {
        content: '完成',
      }],
      dialogMoreControl: false, // 批量处理弹出层
      dialogUploadControl: false, // 上传弹出层
      createTimeRange: "",  // 查询日期
      total: 0, // 数据总条数
      dataList: [],  // 表格数据 
      dataForm: {
        bookName: "",
        beginDate: "",
        endDate: "",
        status: '1',
        current: 1,
        size: 20,
      },// 表单数据
      dataListLoading: false, // 表格 loading 
      tags1: [], // 专家组 
      tags2: [], // 组长 
      tags3: [], // 院长 
      tags4: [], // 书记 
      managerList: [], // 用户列表 名称 id
      uploadBase64Data: '',
      applyForId: null,  // 申请id
      dialogHandlerVisible: false,  // 处理申请弹框是否显示
      fileType: '', // 上传的文件类型
      fileList: []
    };
  },
  created() {
    this.getDataList({})
    this.getList()
  },
  methods: {
    // 关闭详情重置状态
    handerDetailClose() { 
      this.dialogHandlerVisible = false
    },
    // 处理 通过拒绝
    fnNext(status) {
      const params = {
        applyId: this.applyForId,
        status,
      }
      getAuditing(params).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: status === '1' ? "已成功" : "已拒绝"
          });
          this.getDataList()
        }
      }).finally(() => {
        this.dialogHandlerVisible = false
      });
    },
    // 当前登录用户是否是专家组组长
    isAlike() {
      return this.userId === this.leaderUserId ? true : false
    },
    // 处理申请
    handleApplyFor(id, leader_user_id) {
      // 专家组长id
      this.leaderUserId = leader_user_id
      if (!id) return
      this.applyForId = Number(id)
      this.dialogHandlerVisible = true;
    },
    baseToBlob(b64,fileType) {
      const byteCharacters = window.atob(b64)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: fileType? fileType : 'image/png' })
      return blob
    },

    // 上传文件
    handelUploadChange(file) {
      this._toBase64(file.raw).then(res => {
        this.uploadBase64Data = res
        this.fileType = res.split(';')[0].split(':')[1]
      }).catch(err => {
        this.uploadBase64Data = ''
        this._commonMessage(err)
      })
    },
    _toBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          resolve(reader.result);
        };
        reader.onerror = (error) => reject(error);
      });
    },
    // 点击切换 待处理、流程中、已完成
    handleClick(tab) {
      this.dataForm.status = Number(tab.index) + 1 + ''
      this.getDataList()
    },
    // 上传公示结果
    showUploadFile(data) {
      getBookApplyInfo(data.id).then(res => {
        const base64 = res.data.public_file_path.substring(res.data.public_file_path.indexOf(',') + 1)
        if (res.code === 200) {
          const blob = this.baseToBlob(base64,res.data.public_file_type)
          const url = URL.createObjectURL(blob)
          window.open(url)
        } else {
          this._commonMessage(res.msg)
        }

      })
    },
    _resetUpload() {
      this.dialogUploadControl = false
      this.uploadBase64Data = ''
      this.multipleSelection = []
      this.$refs.mainT.clearSelection();
      this.fileList = []
    },
    //  上传确认｜取消
    handelUloadResult(num) {
      const that = this
      if (num === 0) {
        that._resetUpload()
        return
      }
      if (!that.uploadBase64Data) {
        that._commonMessage('您还未上传文件哦')
        return
      }
      const ids = that.multipleSelection.map(item => item.id)
      const data = {
        ids: ids.join(","),
        file: that.uploadBase64Data,
        fileType: that.fileType
      }
      getUploadFile(data).then(res => {
        if (res.code === 200) {
          that._commonMessage('上传公示成功!', 'success')
          that.getDataList()
        } else {
          that._commonMessage(res.msg)
        }
        that._resetUpload()
      })
    },
    //  切换上传文件弹出层
    handleCloseUpload() {
      this.dialogUploadControl = false
      this._resetUpload()
    },
    // 导出
    handelExportOut() {
      // const excelName = `公示材料_${new Date().getTime()}.xlsx`
      // exportExcel(this.$refs.mainT, "公示材料", excelName);
      if (this.multipleSelection.length === 0) {
        this.$alert('请勾选一条或多条信息', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            console.log(action)
          }
        });
        return
      }
      
      const applyIds = this.multipleSelection.map(item => item.id)
      const params = {
        applyIds: applyIds.join(","), // 申请ID集合，int类型
      }

      this.download('/system/audit/exportExcel', params, `book_${new Date().getTime()}.xlsx`)
    },
    // 上传
    handelUpload() {
      if (this.multipleSelection.length > 0) {
        this.dialogUploadControl = true
        return
      }
      this.$alert('请勾选一条或多条信息', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          console.log(action)
        }
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      getUserList().then(res => {
        this.managerList = res.rows.map(item => {
          return {
            value: item.nickName,
            id: item.userId,
            remark: item.remark,
            roleKey: item.roles[0].roleKey
          }
        })
      }
      );
    },
    // 关闭批量列表
    handerMoreClose() {
      this.commonResetMoreStatus()
    },
    //专家组
    getTagData1(p) {
      this.tags1 = p
    },
    //专家组长
    getTagData2(p) {
      this.tags2 = p
    },
    //院长
    getTagData3(p) {
      this.tags3 = p
    },
    //书记
    getTagData4(p) {
      this.tags4 = p
    },
    // 重置批量状态
    commonResetMoreStatus() {
      this.multipleSelection = []
      this.$refs.mainT.clearSelection();
      this.dialogMoreControl = false
      this.getDataList()
    },
    // 定义异常提示
    _commonMessage(message, type = "error") {
      this.$message({
        type,
        message
      });
    },
    // 批量列表的下一步
    fnMoreNext(num) {
      if (num === 0) {
        this.commonResetMoreStatus()
        return
      }
      if (this.tags1.length === 0) {
        this._commonMessage('请指派专家组')
        return
      }
      if (this.tags2.length === 0) {
        this._commonMessage('请指派专家组长')
        return
      }
      if (this.tags3.length === 0) {
        this._commonMessage('请指派院长')
        return
      }
      if (this.tags4.length === 0) {
        this._commonMessage('请指派书记')
        return
      }
      const ids = this.multipleSelection.map(item => item.id)
      const params = {
        expertIds: this.tags1.join(","), // 专家组userid，以逗号分隔
        expertLeaderId: this.tags2[0], // 专家组长id，int类型
        ids: ids.join(","), // 申请ID集合，int类型
        presidentId: this.tags3[0], // 院长id，int类型
        secretaryId: this.tags4[0], // 书记id，int类型

      }
      getUpdateApply(params).then(res => {
        if (res.code === 200) {
          this._commonMessage('批量处理成功!', 'success')
          this.commonResetMoreStatus()
        }
      })

    },
    // 勾选校验
    showMoreControl() {
      if (this.multipleSelection.length > 0) {
        this.dialogMoreControl = true
        return
      }
      this.$alert('请勾选一条或多条信息', '提示', {
        confirmButtonText: '确定',
        callback: action => {

        }
      });
    },

    // 获取多选数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 删除多选数据
    handerDelete(index) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.multipleSelection = this.multipleSelection.filter(item => item.id !== index);
        this._commonMessage('删除成功!', 'success')
        if (this.multipleSelection.length === 0) {
          this.commonResetMoreStatus()
        }
      })

    },
    // 获取审核列表
    getDataList(params = {}) {
      this.dataListLoading = true
      getBookApplyList(Object.assign(this.dataForm, params,{searchType: 2})).then((res) => {
        this.dataList = res?.rows;
        this.total = res?.total;
      }).finally(() => {
        this.dataListLoading = false;
      });

    },
    // 状态处理
    formateStatus(audit_status) {
      if (!audit_status) {
        return '-'
      }
      const statusMap = {
        1: '提交申请',
        2: '初审',
        3: '复审',
        4: '终审',
        5: '公示中',
        6: '完成',
        98: '撤销',
        99: '驳回',
      };

      return statusMap[audit_status] || '-'; // 如果audit_status不在已知键中，则返回'''
    },
    // 序号处理
    indexMethod(index) {
      return index + 1;
    },
    // 开始、结束日期
    changeDate(e) {
      if (e.length > 0) {
        this.dataForm.beginDate = e[0]
        this.dataForm.endDate = e[1]
      }
    },
    // 每页数
    sizeChangeHandle(val) {
      this.getDataList({ current: 1, size: val });
    },
    // 当前页
    currentChangeHandle(val) {
      this.getDataList({ current: val });
    },
    handleSelect(e) {
      Object.assign(this.form, e);
      this.form.bookId = e.id;
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.book_name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  height: 100%;

  .dialogMoreMain {
    padding: 40px;
    height: 100%;
    width: 720px;
    .mainArea {
      background: #fff;
      border-radius: 10px;
      margin: 20px 0;
      padding: 20px;

      .title {
        font-size: 18px;
        font-weight: bold;
        color: #1890ff;
      }

      .item>div:nth-child(1) {
        margin: 20px 20px 10px 20px;
      }
    }
  }

}
</style>
